Week 4: Clustering and classification

date()
## [1] "Wed Nov 24 14:56:05 2021"

This week we will use the data set Boston provided in the R package MASS. The R documentation file for the data can be found here.

# load the data 
library(MASS)

# dimensions
dim(Boston) # 506 observations by 14 variables
## [1] 506  14
# structure
str(Boston) # a data.frame containing numerical data
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
# two of the variables are integers, let's check their unique values
unique(Boston$chas)
## [1] 0 1
unique(Boston$rad)
## [1]  1  2  3  5  4  8  6  7 24

Overview of the data

# load libraries
library(ggplot2)
library(GGally)
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
# graphical overview of the data
ggpairs(Boston, upper = list(continuous = wrap("cor", size=4)))

# summaries
summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

Most of the variables are continuous data, except chas and rad which are integers. The variables have different distributions and only rm shows normal distribution. Variables indus and tax show bimodal distribution, with most of the values falling in the low or the high end of the scale, and less in the middle. Variables crim, zn, nox, dis, lstat and medv are more or less left-skewed whereas variables age, pratio and black are right-skewed. There is strong positive correlation between many of the variables, as between rm and medv, and between nox and age, and strong negative correlation between as between rm and lstat, and between lstat and medv.

Modifing the data set

# standardize the data
boston_scaled <- as.data.frame(scale(Boston))

summary(boston_scaled)
##       crim                 zn               indus              chas        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648  
##       nox                rm               age               dis         
##  Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658  
##  1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049  
##  Median :-0.1441   Median :-0.1084   Median : 0.3171   Median :-0.2790  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617  
##  Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566  
##       rad               tax             ptratio            black        
##  Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033  
##  1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049  
##  Median :-0.5225   Median :-0.4642   Median : 0.2746   Median : 0.3808  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332  
##  Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406  
##      lstat              medv        
##  Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 3.5453   Max.   : 2.9865

The data was standardized by scaling the variables, that is, the column means were subtracted from the corresponding columns and the difference divided by standard deviation. Now the values span between negative and positive, and the difference between the minimum and the maximum value is not as great. Next we will make variable crim into a categorical variable and divide the data set into a training set and a test set.

# load dplyr
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following object is masked from 'package:MASS':
## 
##     select
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
# create categories out of the numerical vector and use the quantiles as break points
bins <- quantile(boston_scaled$crim)

# create categorical variable 'crime' out of 'bins'
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = T)

# replace 'crim' with the categorical variable 'crime'
boston_scaled <- dplyr::select(boston_scaled, -crim) # remove 'crim'
boston_scaled <- data.frame(boston_scaled, crime) # add 'crime'

names(boston_scaled) # check the variable names again
##  [1] "zn"      "indus"   "chas"    "nox"     "rm"      "age"     "dis"    
##  [8] "rad"     "tax"     "ptratio" "black"   "lstat"   "medv"    "crime"
# create training data set using 80% of the data
n <- nrow(boston_scaled) # number of rows in the data set
n80 <- sample(n, size = n * 0.8) # randomly choose 80% of the rows
train <- boston_scaled[n80,] # training set

# create test data set
test <- boston_scaled[-n80,] 

Linear discriminant analysis

We will fit a linear discriminant analysis (LDA) on the train set and use crime as the target variable. All the other variables are predictor variables in the analysis. The crime categories will be predicted from the test data set using the LDA model.

# linear discriminant analysis fit
lda.fit <- lda(crime ~ ., data = train)

# draw a biplot
# function for the biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "orange", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# change the 'crime' classes to numeric
classes <- as.numeric(train$crime)

# draw the plot
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1) # add the arrows

# save the 'crime' categories from the test set and remove the variable from the set
crime_categs <- test$crime # save the crime categories into a new object
test <- dplyr::select(test, -crime) # remove variable crime 

# predict the crime categories in the test set
lda.pred <- predict(lda.fit, newdata = test)

# the results
table(correct = crime_categs, predicted = lda.pred$class)
##                  predicted
## correct           [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
##   [-0.419,-0.411]              17             10               1              0
##   (-0.411,-0.39]                6             18               3              0
##   (-0.39,0.00739]               0              4              16              3
##   (0.00739,9.92]                0              0               0             24

The LDA model fitted using 80% of the original data set performs quite well in predicting the categories of the crime variable. The lowest and the highest crime rates best predicted, but the two categories between these rates are not as easily correctly predicted by the LDA model.

Clustering

# reload the Boston data set
data('Boston')

# scale the data
boston_scaled_2 <- scale(Boston)

# calculate distance between the observations
dist_eu <- dist(boston_scaled_2, method = "euclidean")

# k-means clustering
library(factoextra)
## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa
set.seed(12345)

fviz_nbclust(boston_scaled_2, kmeans, method = "wss") # find the optimal amount of clusters

km <- kmeans(Boston, centers = 3) # optimal number of clusters is 3
km # print the output
## K-means clustering with 3 clusters of sizes 38, 102, 366
## 
## Cluster means:
##         crim       zn     indus       chas       nox       rm      age      dis
## 1 15.2190382  0.00000 17.926842 0.02631579 0.6737105 6.065500 89.90526 1.994429
## 2 10.9105113  0.00000 18.572549 0.07843137 0.6712255 5.982265 89.91373 2.077164
## 3  0.3749927 15.71038  8.359536 0.07103825 0.5098626 6.391653 60.41339 4.460745
##        rad      tax  ptratio     black    lstat     medv
## 1 22.50000 644.7368 19.92895  57.78632 20.44868 13.12632
## 2 23.01961 668.2059 20.19510 371.80304 17.87402 17.42941
## 3  4.45082 311.2322 17.81776 383.48981 10.38866 24.93169
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 
##   3   3   1   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   1   1   3   3   3 
## 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   2   2   2   2 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 
##   2   2   2   2   2   2   2   1   2   2   2   2   2   2   2   2   2   2   2   2 
## 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 
##   2   2   2   2   2   2   2   2   2   1   1   1   1   1   1   1   1   1   1   1 
## 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 
##   2   2   2   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   2 
## 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 
##   2   2   2   2   2   1   2   2   2   2   1   2   2   2   1   1   1   1   2   2 
## 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 
##   2   2   2   2   2   2   1   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   3   3   3   3   3   3   3 
## 501 502 503 504 505 506 
##   3   3   3   3   3   3 
## 
## Within cluster sum of squares by cluster:
## [1]  313208.7  181891.7 2573399.1
##  (between_SS / total_SS =  84.2 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
## [6] "betweenss"    "size"         "iter"         "ifault"
# plot the clusters in a pairplot
pairs(Boston[1:7], col = km$cluster) # show the plot in two halves to make it easier to see

pairs(Boston[8:14], col = km$cluster)